import { View, Text, FlatList, StyleSheet, TouchableOpacity, Image, useWindowDimensions } from 'react-native'
import React, { useContext, useEffect, useState } from 'react'

// 步骤3：子孙组件引入共享上下文对象
// import { GoodsTypesCtx } from '../app/mall/list'
// 从中间模块引入ctx对象
import { GoodsTypesCtx } from '../ctx'

import { zhBorderColor, zhBorderWidth, zhSpacingColBase, zhSpacingColLg, zhSpacingRowBase, zhSpacingRowLg, zhThemeColor, zhThemeColorInverse, zhThemeGrey, zhThemeGreyLight, zhThemeGreyLighter } from '../global'
import { baseURL, mallGoodsList } from '../service'
import { useRouter } from 'expo-router'

export default function ZhTab0() {
  // 步骤4：读取上下文对象中的数据
  const types = useContext(GoodsTypesCtx)
  // console.log(types)
  // 状态变量，记录当前点击的组件的下标
  const [curType,setCurType] = useState(0)
  // 状态变量，保存商品列表
  const [goodsList,setGoodsList] = useState([])
  // 获取屏幕宽度
  const { width } = useWindowDimensions()
  // 计算出图像的宽度
  const imageWidth = (width - 84 - zhSpacingRowBase * 4) / 2
  // 状态变量，保存排序规则
  const [order, setOrder] = useState('soldcount')
  // 状态变量，保存路由对象
  const router = useRouter()

  // 渲染一个商品类别
  const renderType = ({item,index}) => (
    <Text 
      style={[ss.type,curType===index && ss.active]}
      // 点击后，保存当前组件的下标
      onPress={() => {
        setCurType(index)
        // 改回成按照销量排序
        setOrder('soldcount')
      }}
    >
      {item.tname}
    </Text>
  )
  // 渲染一个商品列表
  const renderGoods = ({item}) => {
    return (
      <TouchableOpacity
        activeOpacity={0.6} 
        style={ss.goods}
        onPress={() => router.push('/mall/detail?gid='+item.gid)}
      >
        <Image source={{
          uri: baseURL + item.mainPic
        }} style={{width: imageWidth, height: imageWidth}} />
        {/* numberOfLines 文本最多显示行数，溢出部分用省略号代替 */}
        <Text style={ss.title} numberOfLines={2}>
          {item.goodsName}
        </Text>
        <Text style={ss.count}>月售：{item.soldCount}</Text>
        <View style={ss.priceContainer}>
          {/* 如果存在折扣，才会显示*/}
          {item.discount<1 && <Text style={ss.discountPrice}>
            ￥{(item.originalPrice*item.discount).toFixed(2)}
          </Text>}
          <Text style={[ss.originalPrice,{textDecorationLine: item.discount<1 ? 'line-through' : 'none'}]}>
            ￥{item.originalPrice.toFixed(2)}
          </Text>
        </View>
      </TouchableOpacity>
    )
  }
  // 生命周期：当页面挂载后 + 依赖数据更新
  useEffect(() => {
    ;(async () => {
      // 发送请求
      // 当点击的下标更新，通过下标获取到id
      const data = await mallGoodsList(types.length>0 ? types[curType].tid : 1, order)
      // 将数据保存到状态变量
      setGoodsList(data)
    })()
  }, [curType, order]) 


  return (
    <View style={ss.tabs0}>
      {/* 左侧：商品类别列表  */}
      <FlatList 
        style={ss.typeList}
        data={types}
        renderItem={renderType}
        keyExtractor={item => item.tid}
      />
      {/* 右侧：当前类别下的商品列表 */}
      <View style={ss.goodsContainer}>
        {/* 顶部 */}
        <View style={ss.goodsTop}>
          {/* 只有存在数据后，再显示 */}
          <Text style={ss.discount}>
            {types.length > 0 && types[curType].tname}
          </Text>
          <Text style={ss.soldCount} onPress={() => setOrder('soldcount')}>销量</Text>
          <Text style={ss.price} onPress={() => setOrder(order === 'price-asc' ? 'price-desc' : 'price-asc')}>价格</Text>
        </View>
        {/* 商品列表 */}
        <FlatList
          style={ss.goodsList}
          data={goodsList}
          renderItem={renderGoods}
          numColumns={2}
        />
      </View>
    </View>
  )
}

const ss = StyleSheet.create({
  tabs0: {
    flexDirection: 'row'
  },
  typeList: {
    width: 80, // 宽度
    backgroundColor: zhThemeGreyLighter,
    flexShrink: 0,
    flexGrow: 0
  },
  type: {
    textAlign: 'center',
    paddingVertical: zhSpacingColLg
  },
  active: {
    backgroundColor: zhThemeColor,
    color: zhThemeColorInverse
  },
  goodsContainer: {
    flex: 1,
    marginBottom: zhSpacingColLg * 7
  },
  goodsTop: {
    flexDirection: 'row',
    // backgroundColor: 'pink',
    paddingHorizontal: zhSpacingRowBase,
    paddingVertical: zhSpacingRowBase
  },
  discount: {
    flex: 1,
    color: zhThemeGreyLight
  },
  soldCount: {
    marginRight: zhSpacingRowLg,
    color: zhThemeGreyLight
  },
  price: {
    color: zhThemeGreyLight
  },
  goodsList: {

  },
  goods: {
    width: '50%',
    padding: zhSpacingRowBase,
    borderWidth: zhBorderWidth,
    borderColor: zhBorderColor,
    marginBottom: zhSpacingColLg
  },
  title: {
    fontSize: 15,
    marginVertical: zhSpacingColBase
  },
  count: {
    color: zhThemeGreyLight,
    marginBottom: zhSpacingColBase
  },
  priceContainer: {
    flexDirection: 'row'
  },
  discountPrice: {
    marginRight: zhSpacingRowBase,
    color: '#F00'
  },
  originalPrice: {
    fontSize: 13
  }
})
